<template>
  <div>
    <div style="margin-bottom: 5px">
      <el-button size="large" plain @click="showEdit('add')"
        >新增专题</el-button
      >
    </div>
    <el-row :gutter="10">
      <el-col :span="14">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>专题</span>
            </div>
          </template>
          <Table
            ref="tableRef"
            :columns="columns"
            :showPagination="true"
            :dataSource="tableData"
            :fetch="loadDataList"
            :options="tableOptions"
            @row-click="rowClick"
          >
            <!-- 封面 -->
            <template #cover="{ row }">
              <Cover :cover="row.cover"></Cover>
            </template>
            <template #operation="{ row }">
              <a
                href="javascript:void(0)"
                class="a-link"
                @click="showEdit(row, 'update')"
                >修改</a
              >
              <el-divider direction="vertical" />
              <a href="javascript:void(0)" class="a-link" @click="del(row)"
                >删除</a
              >
            </template>
          </Table>
        </el-card>
      </el-col>
      <el-col :span="10">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>专题文章</span>
            </div>
          </template>
          <div :style="{ 'margin-bottom': '5px' }">
            <el-alert
              title="拖动文章修改排序"
              type="info"
              show-icon
              :closable="false"
            />
          </div>

          <el-tree
            class="tree-panel"
            ref="treeRef"
            :data="blogList"
            default-expand-all
            node-key="bolgId"
            :expand-on-click-node="false"
            :props="treeProps"
            :highlight-current="true"
            draggable="true"
            @node-drop="blogDrag"
          >
            <template #default="{ data }">
              <span class="custom-node-style">
                <span class="node-title">{{ data.title }}</span>
                <span v-if="data.status == 0" :style="{ color: 'red' }"
                  >草稿</span
                >
                <span v-if="data.status == 1" :style="{ color: 'green' }"
                  >已发布</span
                >
                <span class="node-op">
                  <template v-if="data.blogId === '0'">
                    <a
                      class="a-link"
                      href="javascript:void(0)"
                      @click="editBlog('add', data)"
                      >新增文章</a
                    >
                  </template>
                  <template v-else>
                    <a
                      class="a-link"
                      href="javascript:void(0)"
                      @click="showDetail(data)"
                      >预览</a
                    >
                    <el-divider direction="vertical" />

                    <a
                      class="a-link"
                      href="javascript:void(0)"
                      @click="editBlog('update', data)"
                      v-if="userInfo.userId==data.userId"
                      >修改</a
                    >
                    <span v-else>---</span>
                    <el-divider direction="vertical" />

                    <a
                      class="a-link"
                      href="javascript:void(0)"
                      @click="delBlog(data)"
                      v-if="userInfo.userId==data.userId"
                      >删除</a
                    ><span v-else>---</span>
                    <el-divider direction="vertical" />

                    <a
                      class="a-link"
                      href="javascript:void(0)"
                      @click="editBlog('add', data)"
                      >增加下级文章</a
                    >
                  </template>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
        <div class="special-blog-tree"></div>
      </el-col>
    </el-row>

    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      @close="dialogConfig.show = false"
    >
      <el-form
        ref="formDataRef"
        :model="formData"
        :rules="rules"
        label-width="60px"
      >
        <el-form-item label="名称" prop="categoryName">
          <el-input
            placeholder="起一个好听的名字"
            v-model="formData.categoryName"
            size="large"
            ><template #prefix
              ><span class="iconfont icon-title"></span></template
          ></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="cover">
          <CoverUpload v-model="formData.cover"></CoverUpload>
        </el-form-item>
        <el-form-item label="简介" prop="categoryDesc">
          <el-input
            placeholder="这里写简介"
            v-model="formData.categoryDesc"
            size="large"
            type="textarea"
            :autosize="{ minRows: 4, maxRow: 4 }"
            ><template #prefix
              ><span class="iconfont icon-jianjie"></span></template
          ></el-input>
        </el-form-item>
      </el-form>
    </Dialog>

    <BlogEdit ref="BlogEditRef" @callback="saveBlogCallback"></BlogEdit>
    <BlogDetail ref="BlogDetailRef"></BlogDetail>
  </div>
</template>

<script setup>
import BlogDetail from "./BlogDetail.vue";
import BlogEdit from "./BlogEdit.vue";
import VueCookies from "vue-cookies";
import { getCurrentInstance, nextTick, onMounted, reactive, ref } from "vue";
import CoverUpload from "../../components/CoverUpload.vue";
import { dataType } from "element-plus/es/components/table-v2/src/common.mjs";
const { proxy } = getCurrentInstance();

const userInfo = ref(VueCookies.get("userInfo") || {});

const api = {
  loadDataList: "/category/loadCategory4Special",
  saveCategory: "/category/saveCategory4Special",
  deleteCategory: "/category/delCategory4Special",
  getSpecialInfo: "/blog/getSpecialInfo",
  deleteBlog: "/blog/recoveryBlog",
  updateSpecialBlogSort: "/blog/updateSpecialBlogSort",
};

const columns = [
  {
    label: "封面",
    prop: "cover",
    width: 100,
    scopedSlots: "cover",
  },
  {
    label: "名称",
    prop: "categoryName",
    width: 200,
  },
  {
    label: "简介",
    prop: "categoryDesc",
  },
  {
    label: "博客数量",
    prop: "blogCount",
    width: 100,
  },
  {
    label: "操作",
    prop: "operation",
    width: 100,
    scopedSlots: "operation",
  },
];

const tableRef = ref(null);
const tableData = reactive({});
const tableOptions = {
  extHeight: 140,
};

// 默认选择
const currentCateogryId = ref(null);

// 左侧专题列表
const loadDataList = async () => {
  let result = await proxy.Request({
    url: api.loadDataList,
  });
  if (!result) {
    return;
  }
  Object.assign(tableData, result.data);
  if (currentCateogryId.value == null && result.data.list.length > 0) {
    currentCateogryId.value = result.data.list[0].categoryId;
    loadBlogList();
  }
  nextTick(() => {
    tableRef.value.setCurrentRow("categoryId", currentCateogryId.value);
  });
};

//新增,修改
const dialogConfig = reactive({
  show: false,
  title: "标题",

  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

const formData = ref({});
const rules = {
  categoryName: [{ required: true, message: "请输入分类名称" }],
};
const formDataRef = ref();

const showEdit = (type, data) => {
  formData.value.categoryId = undefined;
  dialogConfig.show = true;
  nextTick(() => {
    formDataRef.value.resetFields();
    if (type == "add") {
      dialogConfig.title = "新增分类";
      formData.value = {};
    } else if (type == "update") {
      dialogConfig.title = "编辑分类";
      // 深拷贝
      formData.value = JSON.parse(JSON.stringify(data));
    }
  });
};

const submitForm = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    let params = {};
    Object.assign(params, formData.value);
    let result = await proxy.Request({
      url: api.saveCategory,
      params,
    });
    if (!result) {
      return;
    }

    dialogConfig.show = false;
    proxy.Message.success("保存成功");
    loadDataList();
  });
};

//删除
const del = (data) => {
  proxy.Confirm(`你确定要删除 <b>${data.categoryName}</b> 吗?`, async () => {
    let result = await proxy.Request({
      url: api.deleteCategory,
      params: {
        categoryId: data.categoryId,
      },
    });
    if (!result) {
      return;
    }
    loadDataList();
    currentCateogryId.value = null;
  });
};

//删除博客
const delBlog = (data) => {
  proxy.Confirm(`你确定要删除 <b>${data.title}</b> 吗?`, async () => {
    let result = await proxy.Request({
      url: api.deleteBlog,
      params: {
        blogId: data.blogId,
      },
    });
    if (!result) {
      return;
    }
    loadBlogList();
    loadDataList();
  });
};

// 专题树
const treeProps = {
  children: "children",
  label: "title",
  value: "blogId",
};

// 获取专题文章
const rowClick = (row) => {
  currentCateogryId.value = row.categoryId;
  loadBlogList(currentCateogryId.value);
};

const blogList = ref([]);
const loadBlogList = async () => {
  let result = await proxy.Request({
    url: api.getSpecialInfo,
    params: {
      categoryId: currentCateogryId.value,
      showType: "1",
    },
  });
  blogList.value = result.data;
};

const TreeHeight = ref("");
onMounted(() => {
  setTreeHeight();
});
const setTreeHeight = () => {
  const tableElement = tableRef.value.$el;
  if (tableElement) {
    const height = tableElement.offsetHeight;
    TreeHeight.value = `${height}px`;
  }
};

// 新增,修改,删除 专题博客
const BlogEditRef = ref(null);
const editBlog = (type, data) => {
  BlogEditRef.value.init(type, data);
};

// 保存专题博客回调
const saveBlogCallback = () => {
  loadBlogList();
  loadDataList();
};

// 拖拽方法
const blogDrag = async (draggingNode, dropNode, dropType, ev) => {
  // 拖入某个节点内,修改父级节点为目标节点,同时修改目标节点下的所有子节点的排序
  let parentNode = null;
  if (dropType == "inner") {
    // 拖入某个节点内,修改父节点为目标节点,同时修改目标节点下的所有子节点排序
    parentNode = dropNode;
  } else {
    // 拖入前后,修改被拖动的节点的父节点为目标节点的父节点,同时修改所有父节点下的子节点
    parentNode = dropNode.parent;
  }
  // 操作的节点ID
  const blogId = draggingNode.data.blogId;
  const pBlogId = parentNode.data.blogId;
  // 需要重新排序的博客ID
  const blogIds = [];
  parentNode.childNodes.forEach((element) => {
    blogIds.push(element.data.blogId);
  });
  let params = {
    blogId,
    pBlogId,
    blogIds: blogIds.join(","),
  };
  let result = await proxy.Request({
    url: api.updateSpecialBlogSort,
    params: params,
  });
  if (!result) {
    return;
  }
  getSpecialInfo();
};

// 展示
const BlogDetailRef = ref(null);
const showDetail = (data) => {
  BlogDetailRef.value.showDetail(data);
};
</script>

<style scoped lang="scss">
el-button {
  border-radius: 0;
}

.tree-panel {
  height: calc(100vh - 299px);
  overflow: auto;
  .custom-node-style {
    flex: 1;
    display: flex;
    justify-content: space-between;
  }
}
</style>